package com.yuntsg.nnsfcp.service.back;

import cn.hutool.core.io.FileUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.ds.DSFactory;
import com.alibaba.fastjson.JSONObject;
import com.aspose.words.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuntsg.nnsfcp.common.utils.CheckUtil;
import com.yuntsg.nnsfcp.common.utils.StringUtil;
import com.yuntsg.nnsfcp.common.utils.UserUtil;
import com.yuntsg.nnsfcp.config.AliWuLiuConfig;
import com.yuntsg.nnsfcp.config.UploadConfig;
import com.yuntsg.nnsfcp.entity.BackImEntity;
import com.yuntsg.nnsfcp.entity.BiaoshuEntity;
import com.yuntsg.nnsfcp.entity.ChaXinReport;
import com.yuntsg.nnsfcp.front.entity.*;
import com.yuntsg.nnsfcp.front.mapper.*;
import com.yuntsg.nnsfcp.service.front.AutherService;
import com.yuntsg.nnsfcp.service.front.OrderService;
import com.yuntsg.nnsfcp.service.front.ut.DateUtil;
import com.yuntsg.nnsfcp.service.front.ut.MD5Utils;
import com.yuntsg.nnsfcp.test.bosspdfparsetest.En;
import com.yuntsg.nnsfcp.test.bosspdfparsetest.PDFParse;
import com.yuntsg.nnsfcp.test.bosspdfparsetest.Util;
import com.yuntsg.nnsfcp.test.test.WordInsertTable;
import com.yuntsg.nnsfcp.util.MultipartFileToFileUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BackService {

    @Resource
    DbConfigMapper dbConfigMapper;
    @Resource
    SearchToolsMapper searchToolsMapper;
    @Resource
    HttpSession session;
    @Resource
    UserUtil userUtil;
    @Resource
    MessageMapper messageMapper;
    @Resource
    IcbcPayOrderMapper icbcPayOrderMapper;
    @Resource
    OrderFilesMapper orderFilesMapper;
    @Resource
    TUserRoleMapper tUserRoleMapper;
    @Resource
    TRoleMapper tRoleMapper;
    @Resource
    BidBackCompareMapper bidBackCompareMapper;
    @Resource
    AutherService autherService;
    @Resource
    HttpServletResponse response;
    @Resource
    OrderIndexTimeMapper orderIndexTimeMapper;
    @Resource
    EmployeeMapper employeeMapper;
    @Resource
    WosdetailMapper wosdetailMapper;
    @Resource
    CheckProgressMapper checkProgressMapper;
    @Resource
    HttpServletRequest request;
    @Resource
    TemplateMapper templateMapper;
    @Resource
    OrderBaseInfoMapper orderBaseInfoMapper;
    @Resource
    BidDocumentRecordArticleMapper bidDocumentRecordArticleMapper;
    @Resource
    BidDocumentArticleMapper bidDocumentArticleMapper;
    @Resource
    BidDocumentErrorBackMapper bidDocumentErrorBackMapper;
    @Resource
    CnkiService cnkiService;
    @Resource
    private UploadConfig uploadConfig;
    @Resource
    private AliWuLiuConfig wuLiuConfig;
    @Resource
    private OrderService orderService;

    @SneakyThrows
    public static void main(String[] args) {
        Db use = Db.use(DSFactory.get("server8"));
        Entity query = use.queryOne("select * from db_config where type = 1");
        String info = query.getStr("info");

        String a = info;

        Calendar calendar = Calendar.getInstance();
        String date = "" + calendar.get(Calendar.YEAR) + (calendar.get(Calendar.MONTH) + 1) + calendar.get(Calendar.DATE);
        String fileName = System.currentTimeMillis() + ".docx";
//        String fileNamePdf = fileName.replace(".docx", "") + ".pdf";
        String s1 = "";
        String fromPath = "D:\\Users\\55419\\Desktop\\asd.docx";

        Document doc = new Document(fromPath);
        System.out.println(a);
        String s = handleSearchStrategy(a);
        String ToPath = "/usr/local/gcr/20231110/";
        try {
            File targetFile = new File(ToPath);
            if (!targetFile.exists()) {
                //如果文件夹不存在就创建
                targetFile.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        doc.save(ToPath + fileName);
        System.out.println(s);

    }

    public static String handleSearchStrategy(String strategy) {
        if (StringUtil.isEmpty(strategy)) {
            return "";
        }
        String resStrategy = "";
        // /r 不起作用 直接删除
        strategy = strategy.replace("\r", "");
        if (strategy.contains("/r/n")) {
            resStrategy = strategy.replace("/r/n", ControlChar.LINE_BREAK + "    ");
        } else if (strategy.contains("\n")) {
            resStrategy = strategy.replace("\n", ControlChar.LINE_BREAK + "    ");

        } else {
            resStrategy = strategy;
        }
        return resStrategy;
    }

    public BiaoshuEntity parsePdfToEntity(MultipartFile mfile, File fileF, BackImEntity backImEntity) throws Exception {

        BiaoshuEntity biaoshuEntity = new BiaoshuEntity();
        String fileMD5 = "";
        File file1 = null;
        String saveFilepath = "";
        if (mfile != null) {
            file1 = MultipartFileToFileUtils.multipartFileToFile(mfile);
            fileMD5 = MD5Utils.getFileMD5(file1);
            if (StringUtil.isNull(file1) || StringUtil.isNull(fileMD5)) {
                CheckUtil.check(false, "文件上传错误");
            }
            //进行处理文件入库
            saveFilepath = getSaveFilepath(mfile);
        } else {
            //上级压缩包过来的
            file1 = fileF;
            fileMD5 = MD5Utils.getFileMD5(file1);
            if (StringUtil.isNull(file1) || StringUtil.isNull(fileMD5)) {
                CheckUtil.check(false, "文件上传错误");
            }
            //进行处理文件入库
            saveFilepath = getSaveFilepathF(file1);

        }
        if (StringUtil.isNull(fileMD5)) {
            CheckUtil.check(false, "文件异常");
        }

        List<BidDocumentRecordArticle> fileMd5 = bidDocumentRecordArticleMapper.selectList(new QueryWrapper<BidDocumentRecordArticle>().eq("file_md5", fileMD5));
//        if (fileMd5.size() > 0) {
//            CheckUtil.check(false, "请不要传递重复文件" + fileMd5.get(0).getFileName());
//        }
        BidDocumentRecordArticle bidDocumentRecordArticle = new BidDocumentRecordArticle();
        if (backImEntity != null) {
            //  后台提交过来的 默认是管理员 uid =1
            bidDocumentRecordArticle.setUid(1);
        } else {
            bidDocumentRecordArticle.setUid(userUtil.getFrontUid());
        }

        bidDocumentRecordArticle.setFilePath(saveFilepath);
        bidDocumentRecordArticle.setFileMd5(fileMD5);
        bidDocumentRecordArticle.setFileName(file1.getName());
        bidDocumentRecordArticle.setStat(1);
        List<En.TableText> tableTextList = Util.dellPageInfo(file1);
        String fundTable = "fundTable";
        PDFParse.extractFiled(tableTextList, fundTable, null, biaoshuEntity);
//        bidDocumentRecordArticle.setParseEnti(JSONObject.toJSONString(bidDocumentRecordArticle));
        bidDocumentRecordArticle.setAddt(LocalDateTime.now());
        bidDocumentRecordArticle.setPep(biaoshuEntity.getCover().getApplicant());
        bidDocumentRecordArticle.setProName(biaoshuEntity.getProject().getProjectName());
        bidDocumentRecordArticle.setYearRange(biaoshuEntity.getProject().getResearchPeriod());
        bidDocumentRecordArticle.setSub(biaoshuEntity.getProject().getResearchDirection());
        bidDocumentRecordArticle.setProNo(biaoshuEntity.getCover().getReceivingNumber());
        //2024年10月17日14:09:10 新增加字段
        // level 级别
        // ins  机构
        // bid_type 基金类别
        // dep  部门
        // acce 参与者
        if (backImEntity != null) {
            if (StringUtil.isNotNull(backImEntity.getLevel())) {
                bidDocumentRecordArticle.setLevel(backImEntity.getLevel());
            }
            if (StringUtil.isNotNull(backImEntity.getIns())) {
                bidDocumentRecordArticle.setIns(backImEntity.getIns());
            }
            if (StringUtil.isNotNull(backImEntity.getYear())) {
                bidDocumentRecordArticle.setYearRange(backImEntity.getYear());
            }


        } else {
            bidDocumentRecordArticle.setLevel("国家级");
            bidDocumentRecordArticle.setIns(biaoshuEntity.getCover().getSupportingUnit());
        }
        bidDocumentRecordArticle.setBidType(biaoshuEntity.getCover().getTypesOfFunding());
        bidDocumentRecordArticle.setDep(biaoshuEntity.getCover().getReceivingDepartment());
        List<En.PrincipalInvestigator> principalInvestigatorList = biaoshuEntity.getPrincipalInvestigatorList();
        String acc = String.join(",", principalInvestigatorList.stream().map(o -> o.getFullName()).collect(Collectors.toList()));
        bidDocumentRecordArticle.setAcce(acc);
        bidDocumentRecordArticleMapper.insert(bidDocumentRecordArticle);
        biaoshuEntity.setBdraid(bidDocumentRecordArticle.getId());
        // 添加其他信息 2024年9月29日10:26:10
        biaoshuEntity.setBidName(biaoshuEntity.getCover().getProjectName());
        biaoshuEntity.setBidPro(biaoshuEntity.getCover().getReceivingNumber());
        biaoshuEntity.setSub(biaoshuEntity.getProject().getResearchAttributes());
        biaoshuEntity.setMainPep(biaoshuEntity.getCover().getApplicant());
        biaoshuEntity.setYearRange(biaoshuEntity.getProject().getResearchPeriod());
        biaoshuEntity.setLevel("");
        biaoshuEntity.setProType(biaoshuEntity.getCover().getTypesOfFunding());
        biaoshuEntity.setSupportingUnit(biaoshuEntity.getHostInstitution().getName());


        // 其他信息添加结束
        // 解析 对应文献信息
        extraBidarticle(biaoshuEntity.getArticle_list(), bidDocumentRecordArticle.getId());
        // 原始版本入库
        BidBackCompare bidBackCompare = new BidBackCompare();
        bidBackCompare.setBid(bidDocumentRecordArticle.getId());
        bidBackCompare.setOrg(JSONObject.toJSONString(biaoshuEntity));
        bidBackCompareMapper.insert(bidBackCompare);
        return biaoshuEntity;
    }

    public void addModifyBidInfo(BiaoshuEntity biaoshuEntity) {
        CheckUtil.check(StringUtil.isNotNull(biaoshuEntity.getBdraid()), "数据不完整 id 必填");
        BidBackCompare bidBackCompare = bidBackCompareMapper.selectOne(new QueryWrapper<BidBackCompare>().eq("bid", biaoshuEntity.getBdraid()));
        bidBackCompare.setModi(JSONObject.toJSONString(biaoshuEntity));
        bidBackCompareMapper.updateById(bidBackCompare);
    }

    public void addBidErrorMsg(Integer bidid, String type, String error) {
        BidDocumentErrorBack bidDocumentErrorBack = new BidDocumentErrorBack();
        bidDocumentErrorBack.setUid(userUtil.getFrontUid());
        bidDocumentErrorBack.setBdId(bidid);
        bidDocumentErrorBack.setType(type);
        bidDocumentErrorBack.setTypeMsg(error);
        bidDocumentErrorBackMapper.insert(bidDocumentErrorBack);
    }

    public void extraBidarticle(List<En.BidArticle> bidArticleList, Integer id) {
        if (bidArticleList != null && bidArticleList.size() > 0) {
            for (En.BidArticle bidArticle : bidArticleList) {
                BidDocumentArticle bidDocumentArticle = new BidDocumentArticle();
                bidDocumentArticle.setAddt(LocalDateTime.now());
                bidDocumentArticle.setUid(userUtil.getFrontUid());
                bidDocumentArticle.setBdId(id);
                bidDocumentArticle.setType(bidArticle.getType());
                bidDocumentArticle.setArInfo(bidArticle.getInfo());
                bidDocumentArticle.setArtDoi(bidArticle.getDoi());
                bidDocumentArticle.setStat(2);
                bidDocumentArticleMapper.insert(bidDocumentArticle);

            }
        }
    }

    // 用于判断是不是引文分析和职称论文 2024年7月31日15:58:34
    public boolean checkIsyS(OrderBaseInfo orderBaseInfo) {
        if (StringUtil.isNotNull(orderBaseInfo) && StringUtil.isNotNull(orderBaseInfo.getSearchNewPurpose())) {
            String searchNewPurpose = orderBaseInfo.getSearchNewPurpose();
            if (searchNewPurpose.equals("科研立项") || searchNewPurpose.equals("成果鉴定")) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    public void replaceWordEnd(Document doc, OrderBaseInfo orderBaseInfo) throws Exception {

        if (StringUtil.isNotNull(orderBaseInfo.getGyId())) {
            Employee employee = employeeMapper.selectById(orderBaseInfo.getGyId());
            if (StringUtil.isNotNull(employee)) {


            }
        }
        if (StringUtil.isNotNull(orderBaseInfo.getShId())) {
            Employee employee = employeeMapper.selectById(orderBaseInfo.getShId());
            if (StringUtil.isNotNull(employee)) {


            }
        }

    }

    public String generateToWord(OrderBaseInfo orderBaseInfo, WordFontParam wordFontParam) throws Exception {

        /*
         * 2019年12月12日13:29:23
         * 获取订单作者属性
         * */
        /*
         * 采用模板生成数据
         * */
        String breakLine = ControlChar.LINE_BREAK;
        String pageBreak = ControlChar.PAGE_BREAK;
        Calendar calendar = Calendar.getInstance();
        String date = "" + calendar.get(Calendar.YEAR) + (calendar.get(Calendar.MONTH) + 1) + calendar.get(Calendar.DATE);
        String fileName = System.currentTimeMillis() + ".docx";
//        String fileNamePdf = fileName.replace(".docx", "") + ".pdf";
        String s1 = "";

        String templateId = "";
        //添加判断自动出报告
        String searchNewPurpose = orderBaseInfo.getSearchNewPurpose();

        log.info("当前查新类型++" + searchNewPurpose);

        //  s 是指的职称论文证明 模板开头是 医学科技论文检索报告书
        //y  常规查收查引 对应前台是引文分析
        //C 成果鉴定   K科研立项 ck 模板一致 就是以前的查新模板 不用管
        boolean b = checkIsyS(orderBaseInfo);

        //  templateId 1 查新报告国内
        //  templateId 2 外文医学科技论文检索报告书
        //  templateId 3 引文咨询报告书
        if (!b) {
            templateId = "1";
            log.info("使用查新模板");
        } else {
            if (StringUtil.isNotNull(searchNewPurpose) && searchNewPurpose.equals("引文分析")) {
                templateId = "3";
                log.info("使用引文咨询报告书模板");
            } else {
                templateId = "2";
                log.info("使用外文医学科技论文检索报告书模板");
            }
        }
        if (StringUtil.ObjectIsNotNull(templateId)) {
            CheckUtil.notNull(false, "类型不符 无法自动生成报告");
        }

        String fromPath = "";
        Document doc = null;
        if (templateId.equals("1")) {
            fromPath = request.getServletContext().getRealPath(uploadConfig.getUploadPath() + "/" + "查新报告国内.doc");
            doc = new Document(fromPath);
            ChaXinReport chaXinReport = new ChaXinReport(); //为什么要脱下裤子放个屁啊 还不是为了字段对应好上手吗?
            chaXinReport.setProject_no(orderBaseInfo.getProjectNo() == null ? "" : orderBaseInfo.getProjectNo());
            chaXinReport.setProjectNameCn(orderBaseInfo.getProjectNameCn() == null ? "" : orderBaseInfo.getProjectNameCn());
            chaXinReport.setSearchNewPurpose(orderBaseInfo.getSearchNewPurpose() == null ? "" : orderBaseInfo.getSearchNewPurpose());
            chaXinReport.setSubjectsub(orderBaseInfo.getSubjectSub() == null ? "" : orderBaseInfo.getSubjectSub());
            chaXinReport.setUnitname(orderBaseInfo.getUnitName() == null ? "" : orderBaseInfo.getUnitName());
            chaXinReport.setWtrName(orderBaseInfo.getWtrName() == null ? "" : orderBaseInfo.getWtrName());
            chaXinReport.setPhone(orderBaseInfo.getPhone() == null ? "" : orderBaseInfo.getPhone());
            chaXinReport.setAddress(orderBaseInfo.getAddress() == null ? "" : orderBaseInfo.getAddress());
            chaXinReport.setZipcode(orderBaseInfo.getZipCode() == null ? "" : orderBaseInfo.getZipCode());
            chaXinReport.setAddtime(DateUtil.LocalDateTimeToStringDefault(orderBaseInfo.getAddtime()));
            try {
                chaXinReport.setSlrid(employeeMapper.selectById(orderBaseInfo.getGyId()).getUserName());
            } catch (Exception e) {
                chaXinReport.setSlrid("");

            }
            chaXinReport.setEndtime(DateUtil.LocalDateTimeToStringDefault(orderBaseInfo.getEndtime()));
//            chaXinReport.setCxMainPoint(handleSearchStrategy(orderBaseInfo.getCxMainPoints()));
            chaXinReport.setCxMainPoint(handleSearchStrategy(orderBaseInfo.getSearchRequest() == null ? "" : orderBaseInfo.getSearchRequest()));
            chaXinReport.setNationClass(orderBaseInfo.getNationalClass() == null ? "" : orderBaseInfo.getNationalClass());
            chaXinReport.setSearchKeyCn(orderBaseInfo.getSearchKeyCn() == null ? "" : orderBaseInfo.getSearchKeyCn());
            chaXinReport.setSearchKeyEn(orderBaseInfo.getSearchKeyEn() == null ? "" : orderBaseInfo.getSearchKeyEn());
            chaXinReport.setSearchStrategyCn(orderBaseInfo.getSearchStrategyCn() == null ? "" : orderBaseInfo.getSearchStrategyCn());
            chaXinReport.setSearchStrategyEn(orderBaseInfo.getSearchStrategyEn() == null ? "" : orderBaseInfo.getSearchStrategyEn());

            //工具开始
            chaXinReport.setBackTools(orderBaseInfo.getBackTools() == null ? "" : orderBaseInfo.getBackTools());
            // 检索工具结果 后续在后面进行补充
//        chaXinReport.setSearchToolsRes(handleSearchStrategyNoSpace(orderBaseInfo.getBackToolRes() == null ? "" : orderBaseInfo.getBackToolRes()));
            chaXinReport.setBackYear(orderBaseInfo.getBackYear() == null ? "" : orderBaseInfo.getBackYear());
            chaXinReport.setBackAllsize(orderBaseInfo.getBackAllsize() == null ? "" : orderBaseInfo.getBackAllsize());
            chaXinReport.setBackMatch(orderBaseInfo.getBackMatch() == null ? "" : orderBaseInfo.getBackMatch());
            chaXinReport.setBackMiqie(orderBaseInfo.getBackMiqie() == null ? "" : orderBaseInfo.getBackMiqie());

            //工具结束
            chaXinReport.setCloseArticle(orderBaseInfo.getCloseArticle() == null ? "" : orderBaseInfo.getCloseArticle());
            chaXinReport.setChaxinConclusion(orderBaseInfo.getChaxinConclusion() == null ? "" : orderBaseInfo.getChaxinConclusion());
            if (orderBaseInfo.getDbname() != null && orderBaseInfo.getDbname().equals("国内")) {
                DbConfig type = dbConfigMapper.selectOne(new QueryWrapper<DbConfig>().eq("type", 2));
                String parse = handleSearchStrategy(type.getInfo());
                if (orderBaseInfo.getId() == 23) {
                    FileUtil.writeUtf8String(parse, "/usr/local/gcr/20231110.log");
                }
                chaXinReport.setSearchTools(parse);
            } else {
                DbConfig type = dbConfigMapper.selectOne(new QueryWrapper<DbConfig>().eq("type", 1));
                chaXinReport.setSearchTools(handleSearchStrategy(type.getInfo()));
            }


            // 工具

//        


            //工具结束

            replaceWordEnd(doc, orderBaseInfo);
            // 添加表格编辑
            DocumentBuilder builder = new DocumentBuilder(doc);
            builder.moveToBookmark("cxjl");
            Font font = builder.getFont();
            font.setSize(wordFontParam.getFontSize());
            font.setName(wordFontParam.getFontName());
            font.setSpacing(wordFontParam.getFontSpacing());

            builder.getParagraphFormat().setLineSpacingRule(wordFontParam.getLineSpacingRule());
            builder.getParagraphFormat().setLineSpacing(wordFontParam.getFontSpacing());

            builder.writeln(chaXinReport.getChaxinConclusion());
            font.clearFormatting();
            builder.getParagraphFormat().clearFormatting();


//        builder.moveToField();
            //设置一个书签进行移动到这里添加图标 在word 里面查找
            builder.moveToBookmark("jsjgzb");
            //第一行第一列
            // //垂直居中
//        builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
            //垂直居中 设置里面文字居中
            builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
            //设置此行高度
            builder.getRowFormat().setHeight(29);

            builder.getCellFormat().setLeftPadding(4D);
            builder.getCellFormat().setRightPadding(4D);

            //设置单元格文本的格式
            Border leftNone = builder.getCellFormat().getBorders().getLeft();
            Border righSINGLE = builder.getCellFormat().getBorders().getRight();
            leftNone.setLineStyle(LineStyle.NONE);
            righSINGLE.setLineStyle(LineStyle.SINGLE);
            builder.insertCell();
            builder.write("检索工具种类\n" +
                    "总数");
            builder.insertCell();//插入单元格
            builder.write("检索年限\n" +
                    "（起止年）");
            builder.insertCell();//插入单元格
            builder.write("检索文献\n" +
                    "总量");
            builder.insertCell();//插入单元格
            builder.write("检  出\n" +
                    "文献量");
            Border righNone = builder.getCellFormat().getBorders().getRight();
            righNone.setLineStyle(LineStyle.NONE);
            Border leftSINGLE = builder.getCellFormat().getBorders().getLeft();
            leftSINGLE.setLineStyle(LineStyle.SINGLE);
            builder.insertCell();//插入单元格
            builder.write("密切相关\n" +
                    "文献量");
            builder.endRow();//结束当前行

            Border leftNone3 = builder.getCellFormat().getBorders().getLeft();
            Border righSINGLE3 = builder.getCellFormat().getBorders().getRight();
            leftNone3.setLineStyle(LineStyle.NONE);
            righSINGLE3.setLineStyle(LineStyle.SINGLE);
            builder.insertCell();//插入单元格
            builder.write(chaXinReport.getBackTools());
            builder.insertCell();//插入单元格
            builder.write(chaXinReport.getBackYear());
            builder.insertCell();//插入单元格
            builder.write(chaXinReport.getBackAllsize());
            builder.insertCell();//插入单元格
            builder.write(chaXinReport.getBackMatch());
            Border righNone3 = builder.getCellFormat().getBorders().getRight();
            righNone3.setLineStyle(LineStyle.NONE);
            Border leftSINGLE3 = builder.getCellFormat().getBorders().getLeft();
            leftSINGLE3.setLineStyle(LineStyle.SINGLE);
            builder.insertCell();//插入单元格
            builder.write(chaXinReport.getBackMiqie());
            builder.endRow();//结束当前行
            builder.endTable();


            //水平合并
            // 参数
            //NONE：不合并
            //FIRST：需要合并的第一个单元格
            //PREVIOUS：要与设置FIRST的单元格进行合并的单元格需要设置为PREVIOUS
            Border righNone4 = builder.getCellFormat().getBorders().getRight();
            righNone4.setLineStyle(LineStyle.NONE);
            Border leftSINGLE4 = builder.getCellFormat().getBorders().getLeft();
            leftSINGLE4.setLineStyle(LineStyle.NONE);
            builder.insertCell();//插入单元格
            builder.getCellFormat().setHorizontalMerge(CellMerge.FIRST);
            builder.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
            builder.getRowFormat().setHeight(16);
            builder.write("2．各检索工具检索情况一览表");

            //需要合并的单元格都需要添加PREVIOUS
            builder.insertCell();//插入单元格
            builder.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
            builder.insertCell();
            builder.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
            builder.insertCell();
            builder.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
            builder.insertCell();
            builder.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
            builder.insertCell();
            builder.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
            builder.endRow();//结束当前行
            builder.endTable();
            // 信息显示
            builder.getRowFormat().clearFormatting();
            builder.getCellFormat().clearFormatting();
            builder.getParagraphFormat().clearFormatting();
            builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
            // //垂直居中
            builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
            //设置此行高度
            builder.getRowFormat().setHeight(15);
            //设置单元格文本的格式
            Border leftNone2 = builder.getCellFormat().getBorders().getLeft();
            Border righSINGLE2 = builder.getCellFormat().getBorders().getRight();
            leftNone2.setLineStyle(LineStyle.NONE);
            righSINGLE2.setLineStyle(LineStyle.NONE);
            builder.insertCell();
            builder.write("检索工具体\n" + "(库/刊等)");
            builder.insertCell();//插入单元格
            builder.write("检索年限期\n" + "(起止年)");
            builder.insertCell();//插入单元格
            builder.write("检索文献\n" + "总量");
            builder.insertCell();//插入单元格
            builder.write("检  出\n" + "文献量");
            builder.insertCell();//插入单元格
            builder.write("密切相关\n文献量");
            builder.endRow();//结束当前行

//        builder.getRowFormat().clearFormatting();
//        builder.getCellFormat().clearFormatting();
//        builder.getParagraphFormat().clearFormatting();
//        builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
//        // //垂直居中
//        builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
            //设置此行高度

            List<WordInsertTable.dbInfo> res = new ArrayList<>();
            String type = orderBaseInfo.getNationalClass();
            int typeInt = 0;
            // 1 是国内外 2是国内
            if (StringUtil.isNotNull(type) && type.equals("国内")) {
                typeInt = 2;
            } else {
                typeInt = 1;
            }
            List<SearchTools> pid = searchToolsMapper.selectList(new QueryWrapper<SearchTools>().eq("type", typeInt).eq("pid", orderBaseInfo.getId()).eq("stat", 0));
            for (SearchTools searchTools : pid) {
                WordInsertTable.dbInfo dbInfo = new WordInsertTable.dbInfo();
                dbInfo.setName(searchTools.getName());
                dbInfo.setYearRange(searchTools.getYearRange());
                dbInfo.setSearchSize(searchTools.getSearchSize());
                dbInfo.setSearchReal(searchTools.getSearchReal());
                dbInfo.setSimi(searchTools.getSimi());
                res.add(dbInfo);
            }

            //必须加上 否则出现格式不对 不要让上面的格式影响下面的铺展数据

            builder.getRowFormat().clearFormatting();
            builder.getCellFormat().clearFormatting();
            builder.getParagraphFormat().clearFormatting();
            builder.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
            builder.getRowFormat().setHeight(18);
            // 边框 无显示
            builder.getRowFormat().getBorders().setLineStyle(LineStyle.NONE);
            for (int i = 0; i < res.size(); i++) {
                WordInsertTable.dbInfo re = res.get(i);
                //设置此行高度
                //设置单元格文本的格式
                if (i + 1 == res.size()) {
                    builder.getRowFormat().getBorders().getBottom().setLineStyle(LineStyle.SINGLE);
                }
                builder.insertCell();
                builder.write(re.getName());
                builder.insertCell();
                builder.write(re.getYearRange());
                builder.insertCell();
                builder.write(re.getSearchSize());
                builder.insertCell();
                builder.write(re.getSearchReal());
                builder.insertCell();
                builder.write(re.getSimi());
                builder.endRow();
            }
            builder.endTable();


            //模拟数据 后面设置成真实的
            // 需要把当前node 居左
            builder.moveToBookmark("jsjgzb");
            //让原来的文字居中的居左
            builder.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
            // HorizontalAnchor – 用于计算浮动表水平位置的对象
            //VerticalAnchor – 用于计算浮动表垂直位置的对象
            //AbsoluteHorizontalDistance – 绝对水平浮动表位置
            //AbsoluteVerticalDistance – 绝对垂直浮动表位置
            //AllowOverlap – 启用/禁用与其他浮动对象重叠的选项
            //RelativeHorizontalAlignment – 浮动表相对水平对齐方式。
            //RelativeVerticalAlignment – 浮动表相对垂直对齐方式。
            builder.getRowFormat().clearFormatting();
            builder.getCellFormat().clearFormatting();
            builder.getParagraphFormat().clearFormatting();

            Table Table1 = (Table) doc.getChild(NodeType.TABLE, 0, true);
            Table1.setAlignment(TableAlignment.CENTER);
            Table Table2 = (Table) doc.getChild(NodeType.TABLE, 1, true);
            Table2.setAlignment(TableAlignment.CENTER);
            Table Table3 = (Table) doc.getChild(NodeType.TABLE, 2, true);
            Table3.setAlignment(TableAlignment.CENTER);
            Cell firstCell = Table3.getFirstRow().getLastCell();
            firstCell.getFirstParagraph().getParagraphFormat().setAlignment(CellVerticalAlignment.CENTER);
        } else if (templateId.equals("2")) {
            fromPath = request.getServletContext().getRealPath(uploadConfig.getUploadPath() + "/" + "外文医学科技论文检索报告书.doc");
            doc = new Document(fromPath);
            ChaXinReport chaXinReport = new ChaXinReport();
            chaXinReport.setProject_no(orderBaseInfo.getProjectNo() == null ? "" : orderBaseInfo.getProjectNo());
            chaXinReport.setProjectNameCn(orderBaseInfo.getProjectNameCn() == null ? "" : orderBaseInfo.getProjectNameCn());
            chaXinReport.setSearchNewPurpose(orderBaseInfo.getSearchNewPurpose() == null ? "" : orderBaseInfo.getSearchNewPurpose());
            chaXinReport.setSubjectsub(orderBaseInfo.getSubjectSub() == null ? "" : orderBaseInfo.getSubjectSub());
            chaXinReport.setUnitname(orderBaseInfo.getUnitName() == null ? "" : orderBaseInfo.getUnitName());
            chaXinReport.setWtrName(orderBaseInfo.getWtrName() == null ? "" : orderBaseInfo.getWtrName());
            chaXinReport.setPhone(orderBaseInfo.getPhone() == null ? "" : orderBaseInfo.getPhone());
            chaXinReport.setAddress(orderBaseInfo.getAddress() == null ? "" : orderBaseInfo.getAddress());
            chaXinReport.setZipcode(orderBaseInfo.getZipCode() == null ? "" : orderBaseInfo.getZipCode());
            chaXinReport.setAddtime(DateUtil.LocalDateTimeToStringDefault(orderBaseInfo.getAddtime()));
            try {
                chaXinReport.setSlrid(employeeMapper.selectById(orderBaseInfo.getGyId()).getUserName());
            } catch (Exception e) {
                chaXinReport.setSlrid("");

            }

            chaXinReport.setEndtime(DateUtil.LocalDateTimeToStringDefault(orderBaseInfo.getEndtime()));
//            chaXinReport.setCxMainPoint(handleSearchStrategy(orderBaseInfo.getCxMainPoints()));
            chaXinReport.setCxMainPoint(handleSearchStrategy(orderBaseInfo.getSearchRequest() == null ? "" : orderBaseInfo.getSearchRequest()));
            chaXinReport.setNationClass(orderBaseInfo.getNationalClass() == null ? "" : orderBaseInfo.getNationalClass());
            chaXinReport.setSearchKeyCn(orderBaseInfo.getSearchKeyCn() == null ? "" : orderBaseInfo.getSearchKeyCn());
            chaXinReport.setSearchKeyEn(orderBaseInfo.getSearchKeyEn() == null ? "" : orderBaseInfo.getSearchKeyEn());
            chaXinReport.setSearchStrategyCn(orderBaseInfo.getSearchStrategyCn() == null ? "" : orderBaseInfo.getSearchStrategyCn());
            chaXinReport.setSearchStrategyEn(orderBaseInfo.getSearchStrategyEn() == null ? "" : orderBaseInfo.getSearchStrategyEn());

            //工具开始
            chaXinReport.setBackTools(orderBaseInfo.getBackTools() == null ? "" : orderBaseInfo.getBackTools());
            // 检索工具结果 后续在后面进行补充
//        chaXinReport.setSearchToolsRes(handleSearchStrategyNoSpace(orderBaseInfo.getBackToolRes() == null ? "" : orderBaseInfo.getBackToolRes()));
            chaXinReport.setBackYear(orderBaseInfo.getBackYear() == null ? "" : orderBaseInfo.getBackYear());
            chaXinReport.setBackAllsize(orderBaseInfo.getBackAllsize() == null ? "" : orderBaseInfo.getBackAllsize());
            chaXinReport.setBackMatch(orderBaseInfo.getBackMatch() == null ? "" : orderBaseInfo.getBackMatch());
            chaXinReport.setBackMiqie(orderBaseInfo.getBackMiqie() == null ? "" : orderBaseInfo.getBackMiqie());

            //工具结束
            chaXinReport.setCloseArticle(orderBaseInfo.getCloseArticle() == null ? "" : orderBaseInfo.getCloseArticle());
            chaXinReport.setChaxinConclusion(orderBaseInfo.getChaxinConclusion() == null ? "" : orderBaseInfo.getChaxinConclusion());
            if (orderBaseInfo.getDbname() != null && orderBaseInfo.getDbname().equals("国内")) {
                DbConfig type = dbConfigMapper.selectOne(new QueryWrapper<DbConfig>().eq("type", 2));
                String parse = handleSearchStrategy(type.getInfo());
                if (orderBaseInfo.getId() == 23) {
                    FileUtil.writeUtf8String(parse, "/usr/local/gcr/20231110.log");
                }
                chaXinReport.setSearchTools(parse);
            } else {
                DbConfig type = dbConfigMapper.selectOne(new QueryWrapper<DbConfig>().eq("type", 1));
                chaXinReport.setSearchTools(handleSearchStrategy(type.getInfo()));
            }


            // 工具


            replaceWordEnd(doc, orderBaseInfo);
            //工具结束

        } else if (templateId.equals("3")) {
            fromPath = request.getServletContext().getRealPath(uploadConfig.getUploadPath() + "/" + "引文咨询报告书.doc");
            doc = new Document(fromPath);
            ChaXinReport chaXinReport = new ChaXinReport();
            chaXinReport.setProject_no(orderBaseInfo.getProjectNo() == null ? "" : orderBaseInfo.getProjectNo());
            chaXinReport.setProjectNameCn(orderBaseInfo.getProjectNameCn() == null ? "" : orderBaseInfo.getProjectNameCn());
            chaXinReport.setSearchNewPurpose(orderBaseInfo.getSearchNewPurpose() == null ? "" : orderBaseInfo.getSearchNewPurpose());
            chaXinReport.setSubjectsub(orderBaseInfo.getSubjectSub() == null ? "" : orderBaseInfo.getSubjectSub());
            chaXinReport.setUnitname(orderBaseInfo.getUnitName() == null ? "" : orderBaseInfo.getUnitName());
            chaXinReport.setWtrName(orderBaseInfo.getWtrName() == null ? "" : orderBaseInfo.getWtrName());
            chaXinReport.setPhone(orderBaseInfo.getPhone() == null ? "" : orderBaseInfo.getPhone());
            chaXinReport.setAddress(orderBaseInfo.getAddress() == null ? "" : orderBaseInfo.getAddress());
            chaXinReport.setZipcode(orderBaseInfo.getZipCode() == null ? "" : orderBaseInfo.getZipCode());
            chaXinReport.setAddtime(DateUtil.LocalDateTimeToStringDefault(orderBaseInfo.getAddtime()));
            try {
                chaXinReport.setSlrid(employeeMapper.selectById(orderBaseInfo.getGyId()).getUserName());
            } catch (Exception e) {
                chaXinReport.setSlrid("");

            }

            chaXinReport.setEndtime(DateUtil.LocalDateTimeToStringDefault(orderBaseInfo.getEndtime()));
//            chaXinReport.setCxMainPoint(handleSearchStrategy(orderBaseInfo.getCxMainPoints()));
            chaXinReport.setCxMainPoint(handleSearchStrategy(orderBaseInfo.getSearchRequest() == null ? "" : orderBaseInfo.getSearchRequest()));
            chaXinReport.setNationClass(orderBaseInfo.getNationalClass() == null ? "" : orderBaseInfo.getNationalClass());
            chaXinReport.setSearchKeyCn(orderBaseInfo.getSearchKeyCn() == null ? "" : orderBaseInfo.getSearchKeyCn());
            chaXinReport.setSearchKeyEn(orderBaseInfo.getSearchKeyEn() == null ? "" : orderBaseInfo.getSearchKeyEn());
            chaXinReport.setSearchStrategyCn(orderBaseInfo.getSearchStrategyCn() == null ? "" : orderBaseInfo.getSearchStrategyCn());
            chaXinReport.setSearchStrategyEn(orderBaseInfo.getSearchStrategyEn() == null ? "" : orderBaseInfo.getSearchStrategyEn());

            //工具开始
            chaXinReport.setBackTools(orderBaseInfo.getBackTools() == null ? "" : orderBaseInfo.getBackTools());
            // 检索工具结果 后续在后面进行补充
//        chaXinReport.setSearchToolsRes(handleSearchStrategyNoSpace(orderBaseInfo.getBackToolRes() == null ? "" : orderBaseInfo.getBackToolRes()));
            chaXinReport.setBackYear(orderBaseInfo.getBackYear() == null ? "" : orderBaseInfo.getBackYear());
            chaXinReport.setBackAllsize(orderBaseInfo.getBackAllsize() == null ? "" : orderBaseInfo.getBackAllsize());
            chaXinReport.setBackMatch(orderBaseInfo.getBackMatch() == null ? "" : orderBaseInfo.getBackMatch());
            chaXinReport.setBackMiqie(orderBaseInfo.getBackMiqie() == null ? "" : orderBaseInfo.getBackMiqie());

            //工具结束
            chaXinReport.setCloseArticle(orderBaseInfo.getCloseArticle() == null ? "" : orderBaseInfo.getCloseArticle());
            chaXinReport.setChaxinConclusion(orderBaseInfo.getChaxinConclusion() == null ? "" : orderBaseInfo.getChaxinConclusion());
            if (orderBaseInfo.getDbname() != null && orderBaseInfo.getDbname().equals("国内")) {
                DbConfig type = dbConfigMapper.selectOne(new QueryWrapper<DbConfig>().eq("type", 2));
                String parse = handleSearchStrategy(type.getInfo());
                if (orderBaseInfo.getId() == 23) {
                    FileUtil.writeUtf8String(parse, "/usr/local/gcr/20231110.log");
                }
                chaXinReport.setSearchTools(parse);
            } else {
                DbConfig type = dbConfigMapper.selectOne(new QueryWrapper<DbConfig>().eq("type", 1));
                chaXinReport.setSearchTools(handleSearchStrategy(type.getInfo()));
            }


            // 工具


            replaceWordEnd(doc, orderBaseInfo);
            //工具结束


        }

        String ToPath = request.getServletContext().getRealPath(uploadConfig.getUploadPath() + date + "/");
        try {
            File targetFile = new File(ToPath);
            if (!targetFile.exists()) {
                //如果文件夹不存在就创建
                targetFile.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        doc.save(ToPath + fileName);
//        doc.save(ToPath + fileNamePdf, SaveFormat.PDF);
        //2023年6月14日16:13:32 添加处理签章 初始版不生成pdf版本
        orderBaseInfo.setResultReportWord(uploadConfig.getUploadPath() + date + "/" + fileName);
//        orderBaseInfo.setResultReportPdf(uploadConfig.getUploadPath() + date + "/" + fileNamePdf);
        orderBaseInfoMapper.updateById(orderBaseInfo);
        // 默认返回doc 报告地址
        return uploadConfig.getUploadPath() + date + "/" + fileName;
    }

    //存储文件并且返回文件路径
    @SneakyThrows
    public String getSaveFilepath(MultipartFile file) {
        String s = uplaodFile(file);
        return s;
    }

    @SneakyThrows
    public String getSaveFilepathF(File file) {
        String s = uplaodFileF(file);
        return s;
    }


    public String getDate() {
        Calendar calendar = Calendar.getInstance();
        String date = "" + calendar.get(Calendar.YEAR) + (calendar.get(Calendar.MONTH) + 1) + calendar.get(Calendar.DATE);
        return date;
    }


    /**
     * @param file 传递一个文件
     * @return 路径 返回存在服务器上什么路径里面
     * @throws IOException
     */
    public String uplaodFile(MultipartFile file) throws IOException {
        if (file != null) {
            //20971520 = 20M
//            int fileMaxSize = 20971520;
//            if (file.getSize() > fileMaxSize) {
//                System.out.println("fileSize = " + file.getSize());
//                return "文件太大";
//            }
            //获取文件名
            String fileName = file.getOriginalFilename();
            //处理文件名
            if (fileName != null) {
                String suffix = fileName.substring(fileName.lastIndexOf("."));
                //新的文件名 = UUID+毫秒+后缀
                fileName = System.currentTimeMillis() + suffix;
            }
            //获取年月日,作为"文件夹"的名字
            Calendar calendar = Calendar.getInstance();
            String date = "" + calendar.get(Calendar.YEAR) + (calendar.get(Calendar.MONTH) + 1) + calendar.get(Calendar.DATE);
            //服务器上使用
            //target的目录
            String path = request.getServletContext().getRealPath(uploadConfig.getUploadPath() + date + "/");
            //本地测试
            //String path = "E://uploads/" + date+"/";
            //创建路径
            File targetFile = new File(path);
            if (!targetFile.exists()) {
                //如果文件夹不存在就创建
                targetFile.mkdirs();
            } else {
            }
            //写入
            File newFile = new File(path, fileName);
            if (targetFile != null) {
                file.transferTo(newFile);
            }
            return uploadConfig.getUploadPath() + date + "/" + fileName;
        }
        return null;
    }


    /**
     * @param file 传递一个文件
     * @return 路径 返回存在服务器上什么路径里面
     * @throws IOException
     */
    public String uplaodFileF(File file) throws IOException {
        if (file != null) {
            //20971520 = 20M
//            int fileMaxSize = 20971520;
//            if (file.getSize() > fileMaxSize) {
//                System.out.println("fileSize = " + file.getSize());
//                return "文件太大";
//            }
            //获取文件名
            String fileName = file.getName();
            //处理文件名
            if (fileName != null) {
                String suffix = fileName.substring(fileName.lastIndexOf("."));
                //新的文件名 = UUID+毫秒+后缀
                fileName = System.currentTimeMillis() + suffix;
            }
            //获取年月日,作为"文件夹"的名字
            Calendar calendar = Calendar.getInstance();
            String date = "" + calendar.get(Calendar.YEAR) + (calendar.get(Calendar.MONTH) + 1) + calendar.get(Calendar.DATE);
            //服务器上使用
            //target的目录
            String path = request.getServletContext().getRealPath(uploadConfig.getUploadPath() + date + "/");
            //本地测试
            //String path = "E://uploads/" + date+"/";
            //创建路径
            File targetFile = new File(path);
            if (!targetFile.exists()) {
                //如果文件夹不存在就创建
                targetFile.mkdirs();
            } else {
            }
            //写入
            File newFile = new File(path, fileName);
            FileUtil.copy(file, newFile, false);
            return uploadConfig.getUploadPath() + date + "/" + fileName;
        }
        return null;
    }


}
